package de.hsowl.tod4a.global.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import de.hsowl.tod4a.server.FileWatcher;

public class XMLOutputterHelper {

	private static Logger logger = Logger.getLogger(XMLOutputterHelper.class);
	private XMLOutputter outputter;

	public XMLOutputterHelper(Format format) {
		outputter = new XMLOutputter(format);
	}

	public XMLOutputterHelper() {
		outputter = new XMLOutputter();
	}

	/**
	 * Writes a XML Message to a file
	 * 
	 * @param doc
	 * @param f
	 * @throws IOException
	 */
	public synchronized void output(Document doc, File f) throws IOException {
		long time = System.currentTimeMillis();
		IOException e = null;
		try {
			while (FileWatcher.accessFile(f) == false) {
				try {
					// warten bis file offen
					Thread.sleep(10);
				} catch (Exception ex) {
					logger.error("", ex);
				}
			}

			FileWriter writer = new FileWriter(f);
			outputter.output(doc, writer);
			System.out.println("output() -> " + (System.currentTimeMillis() - time) + "ms");
		} catch (IOException ex) {
			logger.error("", ex);
			e = ex;
		}catch (Exception e2) {
			e2.printStackTrace();
		}
		
		FileWatcher.releaseFile(f);

		if (e != null) {
			throw e;
		}
	}

	/**
	 * Writes a Document to a String
	 * 
	 * @param doc
	 * @return
	 * @throws IOException
	 */
	public synchronized String output(Document doc) throws IOException {
		long time = System.currentTimeMillis();
		StringWriter sw = new StringWriter();
		outputter.output(doc, sw);
		System.out.println("output() -> " + (System.currentTimeMillis() - time) + "ms");
		return sw.toString();
	}

	/**
	 * See {@link XMLOutputter#output(Document, java.io.Writer)}
	 * 
	 * @param newDoc
	 * @param sw
	 * @throws IOException
	 */
	public void output(Document newDoc, StringWriter sw) throws IOException {
		outputter.output(newDoc, sw);
	}
}
